package com.shxc.smarttrade.old.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Matrix;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.shxc.smarttrade.R;
import com.shxc.smarttrade.MyApplication;
import com.shxc.smarttrade.login.activity.LoginHomeActivity;
import com.shxc.smarttrade.old.bean.EventDatas;
import com.shxc.smarttrade.old.bean.OpenTrader;
import com.shxc.smarttrade.old.bean.PendingOrder;
import com.shxc.smarttrade.old.bean.RealTimeQuoteDatas;
import com.shxc.smarttrade.old.bean.StockChartDatas;
import com.shxc.smarttrade.old.bean.SymbolInfo;
import com.shxc.smarttrade.old.bean.SymbolPrice;
import com.shxc.smarttrade.old.constants.EventContents;
import com.shxc.smarttrade.old.constants.URLContents;
import com.shxc.smarttrade.old.fragment.ClosePositionFragment;
import com.shxc.smarttrade.old.fragment.PendingControlFragment;
import com.shxc.smarttrade.old.fragment.StopLossOrProfitFragment;
import com.shxc.smarttrade.old.iview.IViewRealTimeQuote;
import com.shxc.smarttrade.old.iview.IViewStockChart;
import com.shxc.smarttrade.old.myview.CommonAutoRelativeLayout;
import com.shxc.smarttrade.old.myview.MyProgressDialog;
import com.shxc.smarttrade.old.presenter.MainPresenter;
import com.shxc.smarttrade.old.presenter.StockChartPresenter;
import com.shxc.smarttrade.old.utils.Arith;
import com.shxc.smarttrade.old.utils.BaseUtils;
import com.shxc.smarttrade.old.utils.BaseView;
import com.shxc.smarttrade.old.utils.CloseAllActivity;
import com.shxc.smarttrade.old.utils.MyOkHttpUtils;
import com.shxc.smarttrade.old.utils.SpUtils;
import com.umeng.analytics.MobclickAgent;
import com.wordplat.ikvstockchart.InteractiveKLineView;
import com.wordplat.ikvstockchart.KLineHandler;
import com.wordplat.ikvstockchart.entry.Entry;
import com.wordplat.ikvstockchart.entry.EntrySet;
import com.wordplat.ikvstockchart.marker.XAxisTextMarkerView;
import com.wordplat.ikvstockchart.marker.YAxisTextMarkerView;
import com.wordplat.ikvstockchart.render.KLineRender;
import com.wordplat.ikvstockchart.render.TimeLineRender;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.buildins.UIUtil;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView;

import org.greenrobot.eventbus.EventBus;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.shxc.smarttrade.old.utils.Arith.sub;
import static com.mob.MobSDK.getContext;

/**
 * <p>StockChartActivity</p>
 * <p>Date: 2017/5/20</p>
 *
 * @author LYS
 */

public class StockChartUpgradeActivity extends FragmentActivity implements View.OnClickListener, IViewRealTimeQuote, IViewStockChart {
    private static final String TAG = "Activity";

    @BindView(R.id.k_line)
    InteractiveKLineView kLine;
    @BindView(R.id.pb_left)
    ProgressBar pbLeft;
    //    @BindView(R.id.ma_text)
//    TextView maText;
    @BindView(R.id.iv_left)
    ImageView ivLeft;
    @BindView(R.id.tv_big_name)
    TextView tvBigName;
    @BindView(R.id.tv_little_name)
    TextView tvLittleName;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.iv_pending)
    ImageView ivPending;
    @BindView(R.id.tv_account)
    TextView tvAccount;


    //    @BindView(R.id.tv_one)
//    TextView tvOne;
    @BindView(R.id.tv_two)
    TextView tvTwo;
    @BindView(R.id.tv_three)
    TextView tvThree;
    @BindView(R.id.tv_four)
    TextView tvFour;
    @BindView(R.id.tv_five)
    TextView tvFive;
    @BindView(R.id.tv_six)
    TextView tvSix;
    @BindView(R.id.tv_seven)
    TextView tvSeven;
    @BindView(R.id.iv_tag)
    ImageView ivTag;
    @BindView(R.id.rl_left)
    LinearLayout rlLeft;

    @BindView(R.id.btn_main)
    Button btnMain;
    @BindView(R.id.ll_footer)
    LinearLayout llFooter;
    @BindView(R.id.main_tv_buy_rise)
    TextView mainTVBuyRise;
    @BindView(R.id.main_tv_buy_fall)
    TextView mainTVBuyFall;
    @BindView(R.id.ll_close_position)
    LinearLayout llClosePosition;
    @BindView(R.id.ll_hand)
    LinearLayout llHand;
    @BindView(R.id.ll_open_account)
    LinearLayout llOpenAccount;
    @BindView(R.id.iv_arrow)
    ImageView ivArrow;
    @BindView(R.id.tv_spread)
    TextView tvSpread;
    @BindView(R.id.ll_last)
    LinearLayout llLast;

    @BindView(R.id.tv_real_time)
    TextView tvRealTime;
    @BindView(R.id.tv_price_diff)
    TextView tvPriceDiff;
    @BindView(R.id.tv_rate)
    TextView tvRate;
    @BindView(R.id.tv_open)
    TextView tvOpen;
    @BindView(R.id.tv_high)
    TextView tvHigh;
    @BindView(R.id.tv_close)
    TextView tvClose;
    @BindView(R.id.tv_low)
    TextView tvLow;
    @BindView(R.id.ll_k_status)
    LinearLayout llKStatus;
    @BindView(R.id.text_open)
    TextView textOpen;
    @BindView(R.id.text_close)
    TextView textClose;
    @BindView(R.id.text_high)
    TextView textHigh;
    @BindView(R.id.text_low)
    TextView textLow;

    @BindView(R.id.ll_all)
    public CommonAutoRelativeLayout llAll;
    @BindView(R.id.scrollView)
    public ScrollView scrollView;
    @BindView(R.id.magic_indicator)
    MagicIndicator magicIndicator;
    @BindView(R.id.iv_arrow_right)
    ImageView ivArrowRight;

    private Animation animation = null;
    private int offset = 0;//游标的偏移量
    private int tagWidth = 0;//游标的宽度
    private int self = 0;//每块区域自身所在区域坐标
    private TextView textView = null;//当前被选中的TextView
    private String symbol = "";
    private String symbolK = "";
    public int tagFrom;//区分该页面是由哪个界面打开
    private MainPresenter mainPresenter = new MainPresenter(this);
    private StockChartPresenter stockChartPresenter = new StockChartPresenter(this);
    public boolean isPending = false;
    private boolean isKLine = false;//当前展示的是否为K线图

    private long oldTime;//报价时间
    private double oldOpenPrice;//开盘价（某个时间段的）
    private double oldHigt;//最高价（某个时间段的）
    private double oldLow;//最低价（某个时间段的）
    private double oldClose;//收盘价（某个时间段的）
    private long timeDiff;//记录不同时间差
    private List<StockChartDatas.DataBean.QuotesBean> qb;
    private MyProgressDialog shortDialog;
    private StopLossOrProfitFragment stopLossOrProfitFragment;
    private PendingControlFragment pendingControlFragment;
    private ClosePositionFragment closePositionFragment;
    private double accAmt;//账户余额
    private int userId;
    private String phone;
    private int timeLineTag = 0;//用于判断是日分时还是分时 0：日分时 1:分k线图 2：日K图
    private int realDataSize = 0;//真实K线图或分时图集合大小
    private int tagFirst = 0;//判断是否首次进入
    public boolean isOpenAcc = false;//判断是否开户
    private int digits = -1;//价格小数位数
    private TextView TVSUB;
    private int popTag = 0;
    private double yestodayClosePrice = -1;//昨日收盘价
    private double higher = -1;//最高
    private double lower = -1;//最低
    private static final String[] tabName = {"分时", "日线", "周线", "1分钟", "5分钟", "15分钟", "30分钟", "1小时", "4小时", "月线"};
    private List<String> mDataList = Arrays.asList(tabName);
    private int oldPosition = 0;//记录当前K线所属
    private boolean isGetKData = false;//判断是否获取到K线图数据

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    StockChartDatas stockChartDatas = (StockChartDatas) msg.obj;
                    String errCode = stockChartDatas.getErr_code();
                    String errMsg = stockChartDatas.getErr_msg();
                    if (errCode.equals("0")) {
                        isGetKData = true;
                        qb = stockChartDatas.getData().getQuotes();
                        int qbSize = qb.size();

                        if (qb == null || qb.size() == 0) return;
//                        Collections.reverse(qb);
                        oldTime = qb.get(qb.size() - 1).getTime();
                        String d1 = BaseUtils.getDateFromMillionSeconds(oldTime);
                        oldTime = BaseUtils.getMillionSecondsFromDate(d1);

                        oldOpenPrice = qb.get(qb.size() - 1).getOpenPrice();
                        oldHigt = qb.get(qb.size() - 1).getHigh();
                        oldLow = qb.get(qb.size() - 1).getLow();
                        oldClose = qb.get(qb.size() - 1).getClose();
                        mainTVBuyRise.setText(Arith.changePartTextSize(BaseUtils.getDigitsData(qb.get(qb.size() - 1).getClose(), digits), digits));
                        mainTVBuyFall.setText(Arith.changePartTextSize(BaseUtils.getDigitsData(qb.get(qb.size() - 1).getOpenPrice(), digits), digits));

                        EntrySet entrySet = new EntrySet();
                        final int stockMarkerViewHeight = BaseUtils.dip2px(getApplicationContext(), 15);
                        realDataSize = qbSize;
                        for (int i = 0; i < qb.size(); i++) {
                            Long dataStr = qb.get(i).getTime();
                            if (timeLineTag == 0)
                                entrySet.addEntry(new Entry((float) qb.get(i).getOpenPrice(), (float) qb.get(i).getHigh(), (float) qb.get(i).getLow(), (float) qb.get(i).getClose(), qb.get(i).getVol(), dataStr + ""));
                            else {
                                String data = "";
                                if (timeLineTag == 1) {
                                    data = BaseUtils.millionToMinute(dataStr);
                                } else {
                                    data = BaseUtils.millionToDay(dataStr);
                                }
                                entrySet.addEntry(new Entry((float) qb.get(i).getOpenPrice(), (float) qb.get(i).getHigh(), (float) qb.get(i).getLow(), (float) qb.get(i).getClose(), qb.get(i).getVol(), data + ""));
                            }
                        }
                        if (timeLineTag == 0) {
                            for (int i = 0; i < 1440 - qbSize; i++)
                                entrySet.addEntry(new Entry((float) qb.get(qbSize - 1).getOpenPrice(), (float) qb.get(qbSize - 1).getHigh(), (float) qb.get(qbSize - 1).getLow(), (float) qb.get(qbSize - 1).getClose(), qb.get(qbSize - 1).getVol(), 0 + ""));

                        } else if (timeLineTag == -1) {
                            for (int i = 0; i < 480 - qbSize; i++)
                                entrySet.addEntry(new Entry((float) qb.get(qbSize - 1).getOpenPrice(), (float) qb.get(qbSize - 1).getHigh(), (float) qb.get(qbSize - 1).getLow(), (float) qb.get(qbSize - 1).getClose(), qb.get(qbSize - 1).getVol(), 0 + ""));
                        }
                        int intDigit = 0;
                        if (qb.size() > 0) {
                            String str = String.valueOf(qb.get(0).getClose());
                            int index = str.indexOf(".");
                            if (index != -1) {
                                intDigit = index + 1;
                            }

                        }
                        if (isKLine) {//K线图数据
                            kLine.setRender(new KLineRender(getApplicationContext(), digits, intDigit));
                            entrySet.computeStockIndex();//计算其它附带指标
                            kLine.setEntrySet(entrySet);
                            KLineRender kr = (KLineRender) kLine.getRender();
                            //下面两行代码可以控制十字线两端是否有文本展示
                            kr.addMarkerView(new YAxisTextMarkerView(stockMarkerViewHeight, digits));
                            kr.addMarkerView(new XAxisTextMarkerView(stockMarkerViewHeight));
//                            kr.addDrawing(new CurrentTimeDrawing(BaseUtils.getScreenWidth(getApplicationContext())));
                        } else {//分时图数据
//                            Log.e("qb.size", qb.size() + "";
                            kLine.setRender(new TimeLineRender(timeLineTag, realDataSize, digits, intDigit));
                            entrySet.computeStockIndex();
                            kLine.setEntrySet(entrySet);
                            TimeLineRender tr = (TimeLineRender) kLine.getRender();
                            tr.addMarkerView(new YAxisTextMarkerView(stockMarkerViewHeight, digits));
                            tr.addMarkerView(new XAxisTextMarkerView(stockMarkerViewHeight));
//                            tr.addDrawing(new CurrentTimeDrawing(BaseUtils.getScreenWidth(getApplicationContext())));
                        }
                        kLine.notifyDataSetChanged();

//                        if (!TextUtils.isEmpty(symbolK) && tagFrom == 0) {
//                            if (tagFirst == 0)
//                                stockChartPresenter.getSymboLCalInfo(SpUtils.getString(getApplicationContext(), "accessToken", ""), symbolK, SpUtils.getInt(getApplicationContext(), "userId"));
//                        } else if (!TextUtils.isEmpty(symbol) && tagFrom == 1) {
//                            mainPresenter.startRealTimeQuote(symbol);
//                        }
                    } else {
                        showToast(errMsg);
                    }
                    break;
                case 1:
                    String registerURL = (String) msg.obj;
//                    Intent intent = new Intent(StockChartUpgradeActivity.this, OpenAccountActivity.class);
                    MobclickAgent.onEvent(getContext(), "open_account");//友盟统计该点击事件发生次数
//                    intent.putExtra("url", registerURL);
//                    startActivity(intent);
                    startActivity(new Intent(StockChartUpgradeActivity.this, ChooseBrokerActivity.class));
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stock_chart_upgrade);
        CloseAllActivity.getScreenManager().pushActivity(this);
        ButterKnife.bind(this);

        //先判断是否开户登录过
        userId = SpUtils.getInt(this, "userId", -1);
        phone = SpUtils.getString(this, "telephone");
        if (userId == -1) {
            llHand.setVisibility(View.GONE);
            llOpenAccount.setVisibility(View.VISIBLE);
        }
        Intent intent = getIntent();
        symbolK = intent.getStringExtra("symbol");//用于请求K线图的产品名称
        symbol = intent.getStringExtra("symbol");
        digits = intent.getIntExtra("digits", -1);

        tagFrom = intent.getIntExtra("tag", -1);
        String symbolCn = intent.getStringExtra("symbolCn");
        initView();
        initListener();

        tvBigName.setText(symbolCn);
        if (tagFrom == 1) {
            int index = symbol.indexOf(",");
            tvLittleName.setText(symbol.substring(0, index));
            symbolK = symbol.substring(0, index);
        } else
            tvLittleName.setText(symbol);
        tvRight.setText("");
        showShortDialog();
        timeDiff = 1000 * 60;
        //获取今开，昨收，最高，最低数据
        stockChartPresenter.getSymbolPrice(SpUtils.getString(getApplicationContext(), "accessToken", ""), symbolK);
        //获取K线图数据
        initDatas(symbolK, 0);
        if (!TextUtils.isEmpty(symbolK) && tagFrom == 0) {
            stockChartPresenter.getSymboLCalInfo(SpUtils.getString(getApplicationContext(), "accessToken", ""), symbolK, SpUtils.getInt(getApplicationContext(), "userId"));
            mainPresenter.startRealTimeQuote(symbolK);
        } else if (!TextUtils.isEmpty(symbol) && tagFrom == 1) {
            mainPresenter.startRealTimeQuote(symbol);
        }


    }

    /**
     * 初始化view
     */
    private void initView() {

        initBaseView();

        kLine.setKLineHandler(new KLineHandler() {
            @Override
            public void onHighlight(Entry entry, int entryIndex, float x, float y) {
//                final SizeColor sizeColor = kLine.getRender().getSizeColor();
//
//                String maString = String.format(getResources().getString(R.string.ma_highlight),
//                        entry.getMa5(),
//                        entry.getMa10(),
//                        entry.getMa20());
//                Logger.e("close:", entry.getOpen() + "  close:" + entry.getClose() + "  high:" + entry.getHigh() + "  low:" + entry.getLow());

//                maText.setText(getSpannableString(maString,
//                        sizeColor.getMa5Color(),
//                        sizeColor.getMa10Color(),
//                        sizeColor.getMa20Color()));
                llKStatus.setVisibility(View.VISIBLE);
                try {
                    textOpen.setText(String.valueOf(entry.getOpen()));
                    textClose.setText(String.valueOf(entry.getClose()));
                    textHigh.setText(String.valueOf(entry.getHigh()));
                    textLow.setText(String.valueOf(entry.getLow()));
                } catch (Exception e) {
                }
            }

            @Override
            public void onCancelHighlight() {
                llKStatus.setVisibility(View.GONE);

//                String maString = getResources().getString(R.string.ma_normal);
//                maText.setText(maString);
//                Logger.e("cancle", "cancle");
            }

            @Override
            public void onSingleTap(MotionEvent e, float x, float y) {
//                final KLineRender kLineRender = (KLineRender) kLine.getRender();
//
//                if (kLineRender.getKLineRect().contains(x, y)) {
//                    Toast.makeText(StockChartUpgradeActivity.this, "single tab [" + x + ", " + y + "]", Toast.LENGTH_SHORT).show();
//                }
            }

            @Override
            public void onDoubleTap(MotionEvent e, float x, float y) {
                if (kLine.getRender() instanceof KLineRender) {
                    final KLineRender kLineRender = (KLineRender) kLine.getRender();
                    if (kLineRender.getKLineRect().contains(x, y)) {
                        kLineRender.zoomIn(x, y);
                    }
                }
            }

            @Override
            public void onLeftRefresh() {
//                Log.e("left", "onLeftRefresh");
//                pbLeft.setVisibility(View.VISIBLE);
//                // 模拟耗时
//                kLine.postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        pbLeft.setVisibility(View.GONE);
//
//                        List<Entry> entries = new ArrayList<Entry>();
//
//                        kLine.getRender().getEntrySet().insertFirst(entries);
//                        kLine.notifyDataSetChanged();
//                        kLine.refreshComplete(true);
//
//                        if (entries.size() == 0) {
//                            Toast.makeText(StockChartUpgradeActivity.this, "已经到达最左边了", Toast.LENGTH_SHORT).show();
//                        }
//                    }
//                }, 1000);
            }

            @Override
            public void onRightRefresh() {
                kLine.notifyDataSetChanged();
            }
        });
    }

    /**
     * 初始化基础View
     */
    private void initBaseView() {
//        StatusBarUtil.setColor(this, Color.argb(0, 0, 0, 0));//设置状态栏颜色
        final CommonNavigator commonNavigator = new CommonNavigator(this);
//        commonNavigator.setAdjustMode(true);
        commonNavigator.setRightPadding(UIUtil.dip2px(this, 40));
        commonNavigator.setScrollPivotX(0.25f);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return mDataList == null ? 0 : mDataList.size();
            }

            @Override
            public IPagerTitleView getTitleView(final Context context, final int i) {
                final SimplePagerTitleView clipPagerTitleView = new SimplePagerTitleView(context);
                clipPagerTitleView.setText(mDataList.get(i));
                clipPagerTitleView.setNormalColor(Color.parseColor("#666666"));
                clipPagerTitleView.setSelectedColor(Color.parseColor("#ff6200"));
                clipPagerTitleView.setTextSize(BaseUtils.dip2px(context, 4.5f));
                clipPagerTitleView.setPadding(BaseUtils.dip2px(context, 16.0f), 0, BaseUtils.dip2px(context, 16.0f), 0);

                clipPagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (i == oldPosition) return;
                        oldPosition = i;
                        commonNavigator.onPageSelected(i);
                        commonNavigator.onAttachToMagicIndicator();
                        int position = i;
                        if (position == 0) {
                            isKLine = false;
                            showShortDialog();
                            timeLineTag = 0;
                            timeDiff = 1000 * 60;
                            initDatas(symbolK, 0);
                            MobclickAgent.onEvent(getContext(), "day_time");//友盟统计该点击事件发生次数
                        } else if (position == 1) {
                            isKLine = true;
                            showShortDialog();
                            timeLineTag = 2;
                            timeDiff = 1000 * 60 * 60 * 24;
                            initDatas(symbolK, 1440);
                            MobclickAgent.onEvent(getContext(), "one_day_k");//友盟统计该点击事件发生次数
                        } else if (position == 2) {
                            isKLine = true;
                            timeLineTag = 1;
                            showShortDialog();
                            timeDiff = 1000 * 60 * 60 * 24 * 7;
                            initDatas(symbolK, 10080);
                            MobclickAgent.onEvent(getContext(), "one_minute_k");//友盟统计该点击事件发生次数
                        } else if (position == 3) {
                            isKLine = true;
                            showShortDialog();
                            timeLineTag = 1;
                            timeDiff = 1000 * 60;
                            initDatas(symbolK, 1);
                            MobclickAgent.onEvent(getContext(), "five_minute_k");//友盟统计该点击事件发生次数
                        } else if (position == 4) {
                            isKLine = true;
                            showShortDialog();
                            timeLineTag = 1;
                            timeDiff = 1000 * 60 * 5;
                            initDatas(symbolK, 5);
                            MobclickAgent.onEvent(getContext(), "fifteen_minute_k");//友盟统计该点击事件发生次数
                        } else if (position == 5) {
                            isKLine = true;
                            timeLineTag = 1;
                            showShortDialog();
                            timeDiff = 1000 * 60 * 15;
                            initDatas(symbolK, 15);
                            MobclickAgent.onEvent(getContext(), "thirteen_minute_k");//友盟统计该点击事件发生次数
                        } else if (position == 6) {
                            isKLine = true;
                            timeLineTag = 1;
                            showShortDialog();
                            timeDiff = 1000 * 60 * 30;
                            initDatas(symbolK, 30);

                        } else if (position == 7) {
                            isKLine = true;
                            timeLineTag = 1;
                            showShortDialog();
                            timeDiff = 1000 * 60 * 60;
                            initDatas(symbolK, 60);
                        } else if (position == 8) {
                            isKLine = true;
                            timeLineTag = 1;
                            showShortDialog();
                            timeDiff = 1000 * 60 * 60 * 4;
                            initDatas(symbolK, 240);

                        } else if (position == 9) {
                            isKLine = true;
                            timeLineTag = 1;
                            showShortDialog();
                            timeDiff = 1000 * 60 * 60 * 24 * 10;
                            initDatas(symbolK, 43200);
                        }
                    }
                });

                return clipPagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator indicator = new LinePagerIndicator(context);
                indicator.setColors(new Integer[]{Color.parseColor("#ff6200")});
                indicator.setMode(LinePagerIndicator.MODE_EXACTLY);
                indicator.setLineHeight(BaseUtils.dip2px(context, 2));

                return indicator;
            }
        });
        magicIndicator.setNavigator(commonNavigator);


        TVSUB = new TextView(this);
        scrollView.smoothScrollTo(0, 0);
        tvBigName.setText("欧元美元");
        tvLittleName.setText("EURUSD");
        tvRight.setText("品种介绍");
        textView = tvTwo;
        int screenWidth = getResources().getDisplayMetrics().widthPixels;
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) ivTag.getLayoutParams();
        params.width = screenWidth / 6;
//        params.leftMargin = screenWidth * 3 / 7;
        ivTag.setLayoutParams(params);
        Matrix matrix = new Matrix();
        matrix.postTranslate(0, 0);
        ivTag.setImageMatrix(matrix);// 设置动画初始位置
        tagWidth = screenWidth / 6;

        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        if (tagFrom == 0) {
            stopLossOrProfitFragment = new StopLossOrProfitFragment();
            pendingControlFragment = new PendingControlFragment();
            transaction.add(R.id.frame_layout, stopLossOrProfitFragment);
            transaction.add(R.id.frame_layout, pendingControlFragment);
            transaction.show(stopLossOrProfitFragment);
            transaction.hide(pendingControlFragment);
        } else {
            llHand.setVisibility(View.GONE);
            llFooter.setVisibility(View.GONE);
            llClosePosition.setVisibility(View.VISIBLE);
            closePositionFragment = new ClosePositionFragment();
            transaction.add(R.id.frame_layout, closePositionFragment);
            transaction.show(closePositionFragment);
        }

        transaction.commit();
    }

    /**
     * 初始化监听器
     */
    private void initListener() {
        rlLeft.setOnClickListener(this);
        tvRight.setOnClickListener(this);
        ivPending.setOnClickListener(this);
//        tvOne.setOnClickListener(this);
        tvTwo.setOnClickListener(this);
        tvThree.setOnClickListener(this);
        tvFour.setOnClickListener(this);
        tvFive.setOnClickListener(this);
        tvSix.setOnClickListener(this);
        llLast.setOnClickListener(this);

    }

    private SpannableString getSpannableString(String str, int partColor0, int partColor1, int partColor2) {
        String[] splitString = str.split("[●]");
        SpannableString spanString = new SpannableString(str);

        int pos0 = splitString[0].length();
        int pos1 = pos0 + splitString[1].length() + 1;
        int pos2 = pos1 + splitString[2].length() + 1;
        int end = str.length();

        spanString.setSpan(new ForegroundColorSpan(partColor0),
                pos0, pos1, SpannableString.SPAN_EXCLUSIVE_INCLUSIVE);

        spanString.setSpan(new ForegroundColorSpan(partColor1),
                pos1, pos2, SpannableString.SPAN_EXCLUSIVE_INCLUSIVE);

        spanString.setSpan(new ForegroundColorSpan(partColor2),
                pos2, end, SpannableString.SPAN_EXCLUSIVE_INCLUSIVE);

        return spanString;
    }

    /**
     * 初始化K线图历史数据
     *
     * @param symbol
     */
    private void initDatas(String symbol, int type) {
        Map<String, Object> map = new HashMap<>();
        map.put("accessToken", SpUtils.getString(this, "accessToken", ""));
        map.put("symbol", symbol);
        map.put("type", type + "");
        MyOkHttpUtils.getServiceDatas(this,map, URLContents.STOCK_CHART_ACTIVITY_HISTORYQUOTE, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void faild(Call call, Exception e, int id) {
                showToast("网络异常");
                dismissShortDialog();
            }

            @Override
            public void success(String response, int id) {
//                Log.e("StockChart", response);
                Gson gson = new Gson();
                StockChartDatas scd = gson.fromJson(response, StockChartDatas.class);
                Message msg = Message.obtain();
                msg.what = 0;
                msg.obj = scd;
                handler.sendMessage(msg);
                dismissShortDialog();
            }
        });
    }

    @Override
    public void onClick(View v) {
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        switch (v.getId()) {
            case R.id.rl_left:
                finish();
                break;
            case R.id.tv_right:
                break;
//            case R.id.tv_one:
//                goAnimation(0);
//                setTabTextColors(tvOne, textView);
//                textView = tvOne;
//                break;
            case R.id.tv_two:
                goAnimation(0);
                setTabTextColors(tvTwo, textView);
                textView = tvTwo;
                break;
            case R.id.tv_three:
                goAnimation(1);
                setTabTextColors(tvThree, textView);
                textView = tvThree;
                break;
            case R.id.tv_four:
                goAnimation(2);
                setTabTextColors(tvFour, textView);
                textView = tvFour;
                break;
            case R.id.tv_five:
                goAnimation(3);
                setTabTextColors(tvFive, textView);
                textView = tvFive;
                break;
            case R.id.tv_six:
                goAnimation(4);
                setTabTextColors(tvSix, textView);
                textView = tvSix;
                break;
            case R.id.ll_last:
                showPopWindow();
                break;
            case R.id.iv_pending:
                if (isPending) {
                    ivPending.setImageResource(R.mipmap.btn_normal);
                    isPending = false;
                    transaction.show(stopLossOrProfitFragment);
                    transaction.hide(pendingControlFragment);
                    transaction.commit();
                } else {
                    ivPending.setImageResource(R.mipmap.btn_click);
                    isPending = true;
                    transaction.show(pendingControlFragment);
                    transaction.hide(stopLossOrProfitFragment);
                    transaction.commit();
                    MobclickAgent.onEvent(getContext(), "btn_pending");//友盟统计该点击事件发生次数

                }
                setButtonStatus(isPending, stopLossOrProfitFragment.isSetLoseOrProfit, stopLossOrProfitFragment.selectWhatNoPended);
                break;
        }
    }

    /**
     * 展示更多K线图
     */
    private void showPopWindow() {
        ivArrow.setImageResource(R.mipmap.up_icon);
        View view = View.inflate(this, R.layout.pop_more_kline, null);
        final PopupWindow popupWindow = BaseView.showPopupWindowByView(view, this, ivArrow, tvSeven);
        final TextView ff = (TextView) view.findViewById(R.id.tv_ff);
        final TextView first = (TextView) view.findViewById(R.id.tv_first);
        final TextView second = (TextView) view.findViewById(R.id.tv_second);
        final TextView third = (TextView) view.findViewById(R.id.tv_third);
        final TextView fourth = (TextView) view.findViewById(R.id.tv_fourth);

        ff.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {//15分钟
                setPopTextColor(ff, popupWindow, 11);

            }
        });
        first.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {//30分钟
                setPopTextColor(first, popupWindow, 7);
            }
        });

        second.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {//1小时
                setPopTextColor(second, popupWindow, 8);

            }
        });
        third.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {//4小时
                setPopTextColor(third, popupWindow, 9);

            }
        });
        fourth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {//1个月
                setPopTextColor(fourth, popupWindow, 10);

            }
        });

    }

    /**
     * 设置popwindow中字体及背景色
     *
     * @param first
     * @param popupWindow
     */
    private void setPopTextColor(TextView first, PopupWindow popupWindow, int position) {
        goAnimation(5);
        popupWindow.dismiss();
        setTabTextColors(tvSeven, textView);
        textView = tvSeven;
        goAnimation(position);
    }

    /**
     * 执行动画
     */
    private void goAnimation(final int tagPosi) {
        if (tagPosi == 0) {
            self = 0;
            animation = new TranslateAnimation(offset, self, 0, 0);//四参构造函数：第一个参数表述表示动画开始的点离当前View X坐标上的差值！！！差值！！！差值！！！
            offset = 0;
        } else if (tagPosi == 1) {
            self = tagWidth;
            animation = new TranslateAnimation(offset, self, 0, 0);//四参构造函数：第一个参数表述表示动画开始的点离当前View X坐标上的差值！！！差值！！！差值！！！
            offset = tagWidth;
        } else if (tagPosi == 2) {
            self = 2 * tagWidth;
            animation = new TranslateAnimation(offset, self, 0, 0);//四参构造函数：第一个参数表述表示动画开始的点离当前View X坐标上的差值！！！差值！！！差值！！！
            offset = 2 * tagWidth;
        } else if (tagPosi == 3) {
            self = tagWidth * 3;
            animation = new TranslateAnimation(offset, self, 0, 0);//四参构造函数：第一个参数表述表示动画开始的点离当前View X坐标上的差值！！！差值！！！差值！！！
            offset = tagWidth * 3;
        } else if (tagPosi == 4) {
            self = tagWidth * 4;
            animation = new TranslateAnimation(offset, self, 0, 0);//四参构造函数：第一个参数表述表示动画开始的点离当前View X坐标上的差值！！！差值！！！差值！！！
            offset = tagWidth * 4;
        } else if (tagPosi == 5) {
            self = tagWidth * 5;
            animation = new TranslateAnimation(offset, self, 0, 0);//四参构造函数：第一个参数表述表示动画开始的点离当前View X坐标上的差值！！！差值！！！差值！！！
            offset = tagWidth * 5;
        } else if (tagPosi == 6) {
            self = tagWidth * 6;
            animation = new TranslateAnimation(offset, self, 0, 0);//四参构造函数：第一个参数表述表示动画开始的点离当前View X坐标上的差值！！！差值！！！差值！！！
            offset = tagWidth * 6;
        }
        animation.setFillAfter(true);// True:图片停在动画结束位置
        animation.setDuration(200);
        ivTag.startAnimation(animation);
        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
//                if (tagPosi == 0) {
//                    isKLine = false;
//                    showShortDialog();
//                    timeLineTag = -1;
//                    timeDiff = 1000 * 60;
//                    initDatas(symbolK, -1);
//                } else
                if (tagPosi == 0) {
                    isKLine = false;
                    showShortDialog();
                    timeLineTag = 0;
                    timeDiff = 1000 * 60;
                    initDatas(symbolK, 0);
                    MobclickAgent.onEvent(getContext(), "day_time");//友盟统计该点击事件发生次数
                } else if (tagPosi == 1) {
                    isKLine = true;
                    showShortDialog();
                    timeLineTag = 2;
                    timeDiff = 1000 * 60 * 60 * 24;
                    initDatas(symbolK, 1440);
                    MobclickAgent.onEvent(getContext(), "one_day_k");//友盟统计该点击事件发生次数
                } else if (tagPosi == 2) {
                    isKLine = true;
                    timeLineTag = 1;
                    showShortDialog();
                    timeDiff = 1000 * 60 * 60 * 24 * 7;
                    initDatas(symbolK, 10080);
                    MobclickAgent.onEvent(getContext(), "one_minute_k");//友盟统计该点击事件发生次数
                } else if (tagPosi == 3) {
                    isKLine = true;
                    showShortDialog();
                    timeLineTag = 1;
                    timeDiff = 1000 * 60;
                    initDatas(symbolK, 1);
                    MobclickAgent.onEvent(getContext(), "five_minute_k");//友盟统计该点击事件发生次数
                } else if (tagPosi == 4) {
                    isKLine = true;
                    showShortDialog();
                    timeLineTag = 1;
                    timeDiff = 1000 * 60 * 5;
                    initDatas(symbolK, 5);
                    MobclickAgent.onEvent(getContext(), "fifteen_minute_k");//友盟统计该点击事件发生次数
                } else if (tagPosi == 5) {
                    isKLine = true;
                    timeLineTag = 1;
                    showShortDialog();
                    timeDiff = 1000 * 60 * 15;
                    initDatas(symbolK, 15);
                    MobclickAgent.onEvent(getContext(), "thirteen_minute_k");//友盟统计该点击事件发生次数
                } else if (tagPosi == 7) {
                    isKLine = true;
                    timeLineTag = 1;
                    showShortDialog();
                    timeDiff = 1000 * 60 * 30;
                    initDatas(symbolK, 30);
                    tvSeven.setText("30分钟");

                } else if (tagPosi == 8) {
                    isKLine = true;
                    timeLineTag = 1;
                    showShortDialog();
                    timeDiff = 1000 * 60 * 60;
                    initDatas(symbolK, 60);
                    tvSeven.setText("1小时");


                } else if (tagPosi == 9) {
                    isKLine = true;
                    timeLineTag = 1;
                    showShortDialog();
                    timeDiff = 1000 * 60 * 60 * 4;
                    initDatas(symbolK, 240);
                    tvSeven.setText("4小时");


                } else if (tagPosi == 10) {
                    isKLine = true;
                    timeLineTag = 1;
                    showShortDialog();
                    timeDiff = 1000 * 60 * 60 * 24 * 10;
                    initDatas(symbolK, 43200);
                    tvSeven.setText("1个月");


                } else if (tagPosi == 11) {
                    isKLine = true;
                    timeLineTag = 1;
                    showShortDialog();
                    timeDiff = 1000 * 60 * 15;
                    initDatas(symbolK, 15);
                    MobclickAgent.onEvent(getContext(), "thirteen_minute_k");//友盟统计该点击事件发生次数
                    tvSeven.setText("15分钟");
                }
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    /**
     * 设置Tab文本的字体颜色
     */
    private void setTabTextColors(TextView tv1, TextView tv2) {
        popTag = 0;
        if (tv1 != tv2) {
            tv1.setTextColor(getResources().getColor(R.color.main_color));
            tv2.setTextColor(getResources().getColor(R.color.secondary_text_color));
        }
    }

    /**
     * 接收实时数据
     *
     * @param quoteBeen
     */
    @Override
    public void setData(List<RealTimeQuoteDatas.DataBean.QuoteBean> quoteBeen) {
        if (quoteBeen.size() > 0) {
            if (mainTVBuyRise == null) return;

            /**
             *实时修改最大值和最小值
             */

            if (higher > 0 && quoteBeen.get(0).getMarket() > higher) {
                tvHigh.setText(BaseUtils.getDigitsData(quoteBeen.get(0).getMarket(), digits));
                higher = quoteBeen.get(0).getMarket();
            }
            if (lower > 0 && quoteBeen.get(0).getMarket() < lower) {
                tvLow.setText(BaseUtils.getDigitsData(quoteBeen.get(0).getMarket(), digits));
                lower = quoteBeen.get(0).getMarket();
            }

            /**
             *实时价格及其变化率
             */

            if (yestodayClosePrice != -1) {
                double d1 = Arith.sub(quoteBeen.get(0).getMarket(), yestodayClosePrice);
                double d2 = Arith.mul(Arith.div(d1, yestodayClosePrice, 5), 100.0);
                if (d1 > 0) {
                    tvPriceDiff.setTextColor(getResources().getColor(R.color.stock_rise_color));
                    tvRate.setTextColor(getResources().getColor(R.color.stock_rise_color));
                    tvRate.setText("+" + BaseUtils.getDigitsData(d2, 2) + "%");
                    tvPriceDiff.setText("+" + BaseUtils.getDigitsData(d1, digits == -1 ? 2 : digits));

                } else {
                    tvPriceDiff.setTextColor(getResources().getColor(R.color.stock_fell_color));
                    tvRate.setTextColor(getResources().getColor(R.color.stock_fell_color));
                    tvRate.setText(BaseUtils.getDigitsData(d2, 2) + "%");
                    tvPriceDiff.setText(BaseUtils.getDigitsData(d1, digits == -1 ? 2 : digits));
                }
            }

            /**
             * 将数据推送给各fragment片段
             */
            if (stopLossOrProfitFragment != null)
                stopLossOrProfitFragment.setRealTimeDatas(quoteBeen);

            if (pendingControlFragment != null)
                pendingControlFragment.setRealTimeDatas(quoteBeen);

            if (closePositionFragment != null)
                closePositionFragment.setRealTimeDatas(quoteBeen);


            /**
             * 实时修改k线图数据
             */


            Long newTime = quoteBeen.get(0).getTime();
            String n1 = BaseUtils.getDateFromMillionSeconds(newTime);
            newTime = BaseUtils.getMillionSecondsFromDate(n1);
            Double market = quoteBeen.get(0).getMarket();
            String newData = BaseUtils.millionToDate(quoteBeen.get(0).getTime());
            mainTVBuyRise.setText(Arith.changePartTextSize(BaseUtils.getDigitsData(quoteBeen.get(0).getAsk(), digits), digits));
            mainTVBuyFall.setText(Arith.changePartTextSize(BaseUtils.getDigitsData(quoteBeen.get(0).getBid(), digits), digits));
            tvSpread.setText(Arith.format(quoteBeen.get(0).getAsk(), quoteBeen.get(0).getBid(), digits));
            tvRealTime.setText(BaseUtils.getDigitsData(quoteBeen.get(0).getMarket(), digits));

            if (newTime - oldTime < timeDiff) {
                oldHigt = Math.max(market, oldHigt);
                oldLow = Math.min(market, oldLow);
                oldClose = market;
                //更改最后一个数据
                changeLastData(newData, quoteBeen.get(0).getTime());
            } else {

                oldTime = newTime;
                oldOpenPrice = market;
                oldHigt = market;
                oldLow = market;
                oldClose = market;

                if (timeLineTag == 0) {
                    initDatas(symbolK, timeLineTag);//新增分时图数据
                } else {
                    //增加一条K线图新数据
                    EntrySet entrySett = new EntrySet();
                    entrySett.addEntry(new Entry((float) oldOpenPrice, (float) oldHigt, (float) oldLow, (float) oldClose, 0, newData));

                    entrySett.computeStockIndex();
                    List<Entry> entriess = entrySett.getEntryList();
                    kLine.getRender().getEntrySet().addEntries(entriess);
                    kLine.notifyDataSetChanged();
                }
            }


        }

    }

    /**
     * 实时更改最后一条数据
     *
     * @param newData
     */
    private void changeLastData(String newData, long newDate2) {
        EntrySet entrySets = new EntrySet();
        List<Entry> en = kLine.getRender().getEntrySet().getEntryList();
        if (timeLineTag == 0) {
            if (realDataSize > 0 && en.size() > 1) {
                if (en.size() >= realDataSize)
                    en.remove(realDataSize - 1);
                en.add(realDataSize - 1, new Entry((float) oldOpenPrice, (float) oldHigt, (float) oldLow, (float) oldClose, 0, String.valueOf(newDate2)));
            }
        } else {
            if (realDataSize > 0 && en.size() > 1) {
                en.remove(en.size() - 1);
                en.add(new Entry((float) oldOpenPrice, (float) oldHigt, (float) oldLow, (float) oldClose, 0, newData));
            }
        }

        entrySets.addEntries(en);
        entrySets.computeStockIndex();
        kLine.setEntrySet(entrySets);
        kLine.notifyDataSetChanged();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(symbol) && tagFrom == 1) {
            mainPresenter.startRealTimeQuote(symbol);
        }
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        mainPresenter.stopRealTimerQuote();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mainPresenter.stopRealTimerQuote();
        CloseAllActivity.getScreenManager().popActivity(this);
    }

    private MyProgressDialog dialog;

    @Override
    public void showDialog() {
        dialog = new MyProgressDialog(this);
        dialog.setCancelable(false);
        dialog.show();
    }

    @Override
    public void dismissDialog() {
        if (dialog != null)
            dialog.dismiss();
    }

    @Override
    public void showMyToast(String str) {
        showToast(str);
    }

    /**
     * 止盈止损基本数据
     *
     * @param symbolInfo
     */
    @Override
    public void setSymbolCalInfoData(SymbolInfo symbolInfo) {
        isOpenAcc = symbolInfo.isOpenAcc();
        if (isOpenAcc) {//已经开户
            SpUtils.putBoolean(this, "accountStatus", true);
            llHand.setVisibility(View.VISIBLE);
            llOpenAccount.setVisibility(View.GONE);
        } else {
            llHand.setVisibility(View.GONE);
            llOpenAccount.setVisibility(View.VISIBLE);
        }
        tagFirst = 1;
        accAmt = symbolInfo.getAccAmt();
        tvAccount.setText("$" + accAmt);
        if (symbol.equals(symbolInfo.getProfitCalCurrency()))
            symbol += "," + symbolInfo.getMarginCalCurrency();
        else
            symbol += "," + symbolInfo.getMarginCalCurrency() + "," + symbolInfo.getProfitCalCurrency();

        if (stopLossOrProfitFragment != null) {
            stopLossOrProfitFragment.setSymbolCalInfoDatas(symbolInfo);
        }
        if (pendingControlFragment != null) {
            pendingControlFragment.setSymbolCalInfoDatas(symbolInfo);
        }
//        if (!TextUtils.isEmpty(symbol)) {
//            mainPresenter.startRealTimeQuote(symbol);
//        }
    }

    /**
     * 开仓成功后返回值
     *
     * @param openTrader
     */
    @Override
    public void setTradeOpenData(OpenTrader openTrader) {
        tvAccount.setText(sub(accAmt, openTrader.getMargin()) + "");
    }

    @Override
    public void setPendingOrderData(PendingOrder pendingOrder) {

    }

    /**
     * 用于短时间加载的dialog
     */
    public void showShortDialog() {
        shortDialog = new MyProgressDialog(this);
        shortDialog.setCancelable(false);
        shortDialog.show();
    }

    public void dismissShortDialog() {
        shortDialog.dismiss();
    }


    public void showToast(String content) {
        try {
            Toast.makeText(this, content, Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
        }
    }

    /**
     * 从fragment中控制Activity界面Button
     */
    public void setButtonStatus(boolean isPendings, boolean isLossOrProfit, int lossOrprofit) {
        if (isPendings) {
            btnMain.setVisibility(View.VISIBLE);
            llFooter.setVisibility(View.GONE);
            btnMain.setText("确定挂单");

        } else {
            if (isLossOrProfit) {
                btnMain.setVisibility(View.VISIBLE);
                if (lossOrprofit == 0) {
                    btnMain.setText("确定买涨");
                } else {
                    btnMain.setText("确定买跌");
                }
                llFooter.setVisibility(View.GONE);
            } else {
                llFooter.setVisibility(View.VISIBLE);
                btnMain.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 直接买涨按钮
     */
    @OnClick(R.id.main_ll_buy_rise)
    public void mainLLBuyRise() {
        if (userId != -1 && isOpenAcc)
            EventBus.getDefault().post(new EventDatas(EventContents.STOCK_CHART_UPGRADE_ACTIVITY_ONE, ""));
        else
            showMyToast("未开户无法交易");
    }

    /**
     * 直接买跌按钮
     */
    @OnClick(R.id.main_ll_buy_fall)
    public void mainLLBuyFall() {
        if (userId != -1 && isOpenAcc)
            EventBus.getDefault().post(new EventDatas(EventContents.STOCK_CHART_UPGRADE_ACTIVITY_TWO, ""));
        else
            showMyToast("未开户无法交易");
    }

    /**
     * 此处要判断是哪个Fragment中的按钮被点击，同时还要判断是买涨还是买跌
     */
    @OnClick(R.id.btn_main)
    public void btnMain() {
        if (isPending) {//挂单界面
            EventBus.getDefault().post(new EventDatas(EventContents.STOCK_CHART_UPGRADE_ACTIVITY_FOUR, ""));
        } else {//设置止盈止损界面
            EventBus.getDefault().post(new EventDatas(EventContents.STOCK_CHART_UPGRADE_ACTIVITY_THREE, ""));
        }
    }

    /**
     * 调整止损／止盈按钮
     */
    @OnClick(R.id.btn_change_profit_loss)
    public void btnChangProfitLoss() {
        EventBus.getDefault().post(new EventDatas(EventContents.STOCK_CHART_UPGRADE_ACTIVITY_FIVE, ""));
    }

    /**
     * 平仓按钮
     */
    @OnClick(R.id.btn_close_position)
    public void btnClosePosition() {
        EventBus.getDefault().post(new EventDatas(EventContents.STOCK_CHART_UPGRADE_ACTIVITY_SIX, ""));
    }

    private float getRadom(int max, int min) {
        Random radom = new Random();
        float s = radom.nextInt(max) % (max - min + 1) + min;
        return s;
    }

    @OnClick(R.id.iv_recharge)
    public void onViewClicked() {
        startActivity(new Intent(this, RechargeActivity.class));
        MobclickAgent.onEvent(getContext(), "transaction_recharge");//友盟统计该点击事件发生次数
    }


    @OnClick(R.id.btn_open_account)
    public void btnOpnAccount() {
        if (userId == -1) {
            showMyToast("开户前请登录");
            startActivity(new Intent(this, LoginHomeActivity.class));
            MobclickAgent.onEvent(getContext(), "login");//友盟统计该点击事件发生次数

        } else {
//            showDialog();
//            getTangerForeURL(phone, userId);
            MobclickAgent.onEvent(getContext(), "open_account");//友盟统计该点击事件发生次数
            startActivity(new Intent(StockChartUpgradeActivity.this, ChooseBrokerActivity.class));
        }
    }

    /**
     * 获取老虎外汇链接
     *
     * @param phone
     * @param userId
     */
    private void getTangerForeURL(final String phone, int userId) {
        Map<String, Object> map = new HashMap<>();
        map.put("accessToken", SpUtils.getString(this, "accessToken", ""));
        map.put("userId", userId + "");
        map.put("phone", phone);
        MyOkHttpUtils.getServiceDatas(this,map, URLContents.ACCOUNT_FRAGMENT_REGISTERURL, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void faild(Call call, Exception e, int id) {
                MyApplication.showToast(getContext(), getString(R.string.net_error));
                dismissDialog();
            }

            @Override
            public void success(String response, int id) {
                dismissDialog();
                if (response == null || new JsonParser().parse(response).isJsonNull()) {
                    MyApplication.showToast(getContext(), getString(R.string.data_error));
                    return;
                }
                JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
                String errCode = "";
                String errMsg = "";
                if (!jsonObject.get("err_code").isJsonNull())
                    errCode = jsonObject.get("err_code").getAsString();
                if (!jsonObject.get("err_msg").isJsonNull())
                    errMsg = jsonObject.get("err_msg").getAsString();
                if (errCode.equals("0")) {
                    JsonObject data = jsonObject.get("data").getAsJsonObject();
                    String registerURL = "";
                    if (!data.get("registerURL").isJsonNull())
                        registerURL = data.get("registerURL").getAsString();
                    Message msg = Message.obtain();
                    msg.what = 1;
                    msg.obj = registerURL;
                    handler.sendMessage(msg);
                } else {
                    MyApplication.showToast(getContext(), errMsg);
                }
            }
        });
    }

    @Override
    public void setSymbolPrice(SymbolPrice symbolPrice) {
        if (tvHigh == null) return;
        tvOpen.setText(BaseUtils.getDigitsData(symbolPrice.getTodayOpenPrice(), digits));
        tvClose.setText(BaseUtils.getDigitsData(symbolPrice.getYesterdayClosePrice(), digits));
        tvHigh.setText(BaseUtils.getDigitsData(symbolPrice.getTodayHigh(), digits));
        tvLow.setText(BaseUtils.getDigitsData(symbolPrice.getTodayLow(), digits));
        yestodayClosePrice = symbolPrice.getYesterdayClosePrice();
        higher = symbolPrice.getTodayHigh();
        lower = symbolPrice.getTodayLow();
    }


}
